package pr.iceworld.fernando.oms.web;

import org.springframework.web.bind.annotation.*;
import pr.iceworld.fernando.entity.User;
import pr.iceworld.fernando.entity.res.ResponseResult;
import pr.iceworld.fernando.oms.exception.ResourceNotFound;
import pr.iceworld.fernando.oms.service.UserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/users")
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseResult<List<User>> list() {
        ResponseResult<List<User>> responseResult = ResponseResult.ok(userService.getAll());
        return responseResult;
    }

    @RequestMapping(value = "/rolesAndPermissions", method = RequestMethod.GET)
    public ResponseResult<List<User>> rolesAndPermissions() {
        ResponseResult<List<User>> responseResult = ResponseResult.ok(userService.getUserRolePermission(null));
        return responseResult;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseResult<User> getValue(@PathVariable(name = "id") Long id) {
        User param = new User();
        param.setId(id);
        User result = userService.getOne(param);
        if (Objects.isNull(result)) {
            throw new ResourceNotFound(String.valueOf(id));
        }
        ResponseResult<User> responseResult = ResponseResult.ok(result);
        return responseResult;
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public ResponseResult<User> putValue(User user) {
        User result = userService.getOne(user);
        userService.update(user);
        if (Objects.isNull(result)) {
            throw new ResourceNotFound(String.valueOf(user.getId()));
        }
        ResponseResult<User> responseResult = ResponseResult.ok(result);
        return responseResult;
    }

    @ExceptionHandler(ResourceNotFound.class)
    public ResponseResult handlerException(ResourceNotFound e) {
        ResponseResult result = new ResponseResult();
        result.setStatus(ResponseResult.STATUS_FAIL);
        result.setMessage(e.getMessage());
        return result;
    }
}
